<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/9/20
 * Time: 15:57
 */

namespace app\api\controller;


use app\api\model\DataModel;
use app\common\wechat\WXBizMsgCrypt;
use think\Config;
use think\Controller;
use think\Log;

class Start extends Controller
{
    public function index()
    {
        if (isset($_GET['phpinfo'])) {
            phpinfo();
            echo '
            <script>
                ws = new WebSocket("wss://172.17.18.5:2346");
                ws.onopen = function() {
                    alert("连接成功");
                    ws.send(\'tom\');
                    alert("给服务端发送一个字符串：tom");
                };
                ws.onmessage = function(e) {
                    alert("收到服务端的消息：" + e.data);
                };
                </script>
            ';
        }
        return 'This\'s suYong Studio API.<script>console.log("%c suYong %c Copyright \xa9 2016-%s Design by XCloudStudio",\'font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size:64px;color:#00bbee;-webkit-text-fill-color:#00bbee;-webkit-text-stroke: 1px #00bbee;\',"font-size:12px;color:#999999;",(new Date).getFullYear());console.log(\'温馨提示：请不要调皮地在此粘贴执行任何内容，这可能会导致您的账户受到攻击，给您带来损失 ！^_^\');</script>';
    }

    public function ticket()
    {
        if (empty($_GET)) {
            return 'think for your Watch!';
        }
        $encryptMsg = file_get_contents('php://input');
        $timeStamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $encrypt_type = $_GET['encrypt_type'];
        $msg_sign = $_GET['msg_signature'];
        $signature = $_GET['signature'];
        $result = $this->getVerify_Ticket($signature, $timeStamp, $nonce, $encrypt_type, $msg_sign, $encryptMsg);
        if ($result) {
            echo "success";
        } else {
            echo "failed";
        }
        exit();
    }

    private function getVerify_Ticket($signature, $timeStamp, $nonce, $encrypt_type, $msg_sign, $encryptMsg)
    {

        $Encrypt = simplexml_load_string($encryptMsg, 'SimpleXMLElement', LIBXML_NOCDATA)->Encrypt; // 消息数据

        $from_xml = sprintf("<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>", $Encrypt);

        $SDK = new WXBizMsgCrypt(Config::get('wxopen.token'), Config::get('wxopen.encodeKey'), Config::get('wxopen.appid'));

        $msg = '';
        if ($SDK->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg) == 0) {
            $RES = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
            switch ($RES->InfoType) {
                case 'component_verify_ticket':
                    $data = [
                        'encrypt_type' => $encrypt_type,
                        'timestamp' => $timeStamp,
                        'nonce' => $nonce,
                        'msg_signature' => $msg_sign,
                        'signature' => $signature,
                        'errCode' => 0,
                        'component_verify_ticket' => $RES->ComponentVerifyTicket,
                        'add_time' => date('y-m-d H:i:s', time())
                    ];
                    $openModel = new DataModel();
                    if ($openModel->changeInfo('open_ticket', $data)) {
                        return true;
                    }
                    break;
                case 'authorized':
                    return true;
                    break;
                case 'unauthorized':
                    return true;
                    break;
                default:
                    Log::error('+++++++++++++++++++  授权通知接口  +++++++++++++++++++++');
                    Log::error('回调类型：' . $RES->InfoType);
                    Log::error('无效的内容：' . $msg);
                    break;
            }
        } else {
            Log::error('Start 异步发生异常：' . $msg);
            return true;
        }
        return true;
    }
}